package org.fglxy.mockserver.netty.dynamic;

import org.fglxy.mockserver.entity.MockMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.Message;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 将json转为动态proto消息
 * @author xiaoyangliu
 *
 */
public class DynamicProtoEncode extends MessageToByteEncoder<MockMessage> {
	private Logger LOGGER = LoggerFactory.getLogger(DynamicProtoEncode.class);
	
	
	@Override
	protected void encode(ChannelHandlerContext ctx, MockMessage msg, ByteBuf out) throws Exception {
		if (msg == null) return;
		//获取要传输的协议内容
		int cmdNo = msg.getCmdNo();
		byte[] datas = null;
		//透传逻辑
		if (msg.getBytes() != null) {
			datas = msg.getBytes();
		}
		//编码
		else {
			Message proto = msg.getMsg();
			datas = proto.toByteArray();
		}
		out.writeShortLE(datas.length);
		out.writeShortLE(cmdNo);
		out.writeBytes(datas);
		LOGGER.info("cmdNo:{};length:{}", cmdNo, datas.length);
	}

}
